package com.moon.utils;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

/**
 * 图片cache (L1 cache)
 * 
 * @author paul
 * @date 2014年5月27日
 */
public class BitmapImageCache implements ImageCache {

    private static BitmapImageCache cache;

    public static ImageCache getInstance() {
        if (cache == null) {
            cache = new BitmapImageCache();
        }
        return cache;
    }

    //Lru实现的L1缓存
    LruCache<String, Bitmap> mCache;

    private BitmapImageCache() {
        // 获取应用程序最大可用内存  
        int maxMemory = (int) Runtime.getRuntime().maxMemory();

        // 设置图片缓存大小为程序最大可用内存的1/8
        int cacheSize = maxMemory / 8;
        mCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getByteCount();
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {
        return mCache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        mCache.put(url, bitmap);
    }

    //方便清除key  让外部取得LruCache
    public LruCache<String, Bitmap> getLruCache() {
        return mCache;
    }

}
